/**
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2022-03-23 09:15:50
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\common\project\store\modules\user.js
 * @CIMC-V2
 */
/**
 * @description 登录、获取用户信息、退出登录、清除token逻辑，不建议修改
 */
import qs from 'qs'
import { getUserInfo, login, switchWarehouse } from '@commonProject/api/user'
import { setStorage, getStorage, clearStorage, getUrlSystemApp } from '@/utils/tools'
import { menuToRoutes, GFCD } from '@/utils/utils'
import { resetRouter } from '@commonProject/router'
import { isArray, isString } from '@/utils/validate'
import { tokenName, independent, loginMessage } from '@project/config'
import WebSocketConnect from '@commonProject/socket/WebSocketConnect'

import { gp } from '@vui'
import isEmpty from 'lodash/isEmpty'

import router from './../../router/index'

import Watermark from '@/utils/watermark'
import { constantStr } from '@/utils/constantStr'

import astrict from '@/utils/astrict'
import { translateTitle } from '@/utils/i18n'
import cloneDeep from 'lodash/cloneDeep'

const state = () => ({
  uid: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`uid_${getUrlSystemApp()}`) || '',
  language: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`language`) || '',
  menuBtns: process.env.VUE_APP_BuildProject === 'pda' ? [] : getStorage(`menuBtns_${getUrlSystemApp()}`) || [],
  token: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`token_${getUrlSystemApp()}`) || '',
  menu: process.env.VUE_APP_BuildProject === 'pda' ? [] : getStorage(`menu_${getUrlSystemApp()}`) || [],
  username: 'Test',
  apps: process.env.VUE_APP_BuildProject === 'pda' ? [] : getStorage(`apps_${getUrlSystemApp()}`) || [], //所有应用
  appId: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`appId_${getUrlSystemApp()}`) || '', //应用id
  appCode: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`appCode_${getUrlSystemApp()}`) || '', //应用Code
  orgCode: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`orgCode_${getUrlSystemApp()}`) || '', //组织Code
  warehouseList: process.env.VUE_APP_BuildProject === 'pda' ? [] : getStorage(`warehouseList_${getUrlSystemApp()}`) || [],
  wareHoseId: process.env.VUE_APP_BuildProject === 'pda' ? '' : getStorage(`wareHoseId_${getUrlSystemApp()}`) || '',
  constant: process.env.VUE_APP_BuildProject === 'pda' ? {} : getStorage(`constant_${getUrlSystemApp()}`) || {},
  pdaUrl: '',
  businessCode: getStorage(`businessCode_${getUrlSystemApp()}`) || {},
  appCodeUrl: getStorage(`appCodeUrl_${getUrlSystemApp()}`) || '',
})
const getters = {
  appCodeUrl: (state) => state.appCodeUrl,
  businessCode: (state) => state.businessCode,
  uid: (state) => state.uid,
  language: (state) => state.language,
  pdaUrl: (state) => state.pdaUrl,
  menuBtns: (state) => state.menuBtns,
  menu: (state) => state.menu,
  token: (state) => state.token,
  username: (state) => state.username,
  apps: (state) => {
    if (isEmpty(state.appId)) {
      if (state.apps.length > 0) state.apps[0].active = true
    } else {
      state.apps.forEach((v) => {
        if (v.ID == state.appId) {
          v.active = true
        }
      })
    }
    return state.apps
  },
  appId: (state) => state.appId,
  appCode: (state) => state.appCode,
  orgCode: (state) => state.orgCode,
  getAppInfo: (state) => {
    console.log('state.apps', state.apps)
    return state.apps.find((item) => item.ID === state.appId) || {}
  },
  warehouseList: (state) => {
    if (isEmpty(state.wareHoseId)) {
      if (state.warehouseList && state.warehouseList.length > 0) {
        state.warehouseList[0].active = true
      }
    } else {
      if (isArray(state.warehouseList)) {
        state.warehouseList.forEach((v) => {
          if (v.WAREHOUSE_ID == state.wareHoseId) {
            v.active = true
          }
        })
      }
    }
    return state.warehouseList
  },
  wareHoseId: (state) => state.wareHoseId,

  getConstant: (state) => state.constant,
}
const mutations = {
  /**
   * @description 组件中请求的URL
   * @param {*} state
   * @param {*} uid
   */
  setappCodeUrl(state, appCodeUrl) {
    state.appCodeUrl = appCodeUrl
    setStorage(`appCodeUrl_${getUrlSystemApp()}`, appCodeUrl)
  },
  /**
   * @description 业务code(如 WMS：ORG_ID,WAREHOSE_ID;DAMS:ORG_ID)
   * @param {*} state
   * @param {*} uid
   */
  setbusinessCode(state, businessCode) {
    state.businessCode = businessCode
    setStorage(`businessCode_${getUrlSystemApp()}`, businessCode)
  },
  /**
   * @description 设置uid
   * @param {*} state
   * @param {*} uid
   */
  setUid(state, uid) {
    state.uid = uid
    setStorage(`uid_${getUrlSystemApp()}`, uid)
  },
  /**
   * @description 设置uid
   * @param {*} state
   * @param {*} uid
   */
  setLanguage(state, language) {
    state.language = language
    setStorage(`language`, language)
  },
  /**
   * @description 设置菜单btns
   * @param {*} state
   * @param {*} uid
   */
  setMenuBtns(state, menuBtns) {
    state.menuBtns = menuBtns
    setStorage(`menuBtns_${getUrlSystemApp()}`, menuBtns)
  },
  /**
   * @description 设置token
   * @param {*} state
   * @param {*} token
   */
  setToken(state, token) {
    console.log('设置token', token)
    console.log('重置token=========', `token_${getUrlSystemApp()}`, window.location.href)
    state.token = token
    setStorage(`token_${getUrlSystemApp()}`, token)
  },
  /**
   * @description 设置menu
   * @param {*} state
   * @param {*} menu
   */
  setMenu(state, menu) {
    state.menu = menu
    setStorage(`menu_${getUrlSystemApp()}`, menu)
  },
  /**
   * @description 设置用户名
   * @param {*} state
   * @param {*} username
   */
  setUsername(state, username) {
    state.username = username
  },
  /**
   * @description 设置应用列表
   * @param {*} state
   * @param {*} id
   */
  setApps(state, apps) {
    state.apps = apps
    setStorage(`apps_${getUrlSystemApp()}`, apps)
  },
  /**
   * @description 设置应用ID
   * @param {*} state
   * @param {*} id
   */
  setAppId(state, appid) {
    state.appId = appid
    setStorage(`appId_${getUrlSystemApp()}`, appid)
  },
  /**
   * @description 设置应用CODE
   * @param {*} state
   * @param {*} id
   */
  setAppCode(state, appCode) {
    state.appCode = appCode
    setStorage(`appCode_${getUrlSystemApp()}`, appCode)
  },
  /**
   * @description 设置组织CODE
   * @param {*} state
   * @param {*} id
   */
  setOrgCode(state, orgCode) {
    state.orgCode = orgCode
    setStorage(`orgCode_${getUrlSystemApp()}`, orgCode)
  },
  /**
   * @description 设置仓库列表
   */
  setWarehouseList(state, list) {
    state.warehouseList = list
    setStorage(`warehouseList_${getUrlSystemApp()}`, list)
  },
  /**
   * @description 设置仓库id
   */
  setFirstWareHoseId(state, id) {
    state.wareHoseId = id
    setStorage(`wareHoseId_${getUrlSystemApp()}`, id)
  },
  /**
   * @description 设置常量
   */
  setConstant(state, val) {
    state.constant = val
    setStorage(`constant_${getUrlSystemApp()}`, val)
  },
}
const actions = {
  /**
   * @description 登录
   * @param {*} { commit }
   * @param {*} userInfo
   */
  async login({ commit }, userInfo) {
    // userInfo.LOGIN_ENTRANCE = 'PC' //在login调用时候传LOGIN_ENTRANCE参数
    const { data } = await login(userInfo)
    if (data.toUpdatePassWordPage == 'Y' && process.env.VUE_APP_BuildProjectType !== 'mobile') {
      gp.$baseMessage(data.passwordWarnTime ? data.passwordWarnTime + '/n' + data.exprieToken : data.exprieToken, 'warning')
      setTimeout(() => {
        router.push({ path: '/resetPassword', query: { USER_ID: userInfo.USER_ID } })
      })
    } else if (data.token) {
      if (data.passwordWarnTime) gp.$baseMessage(data.passwordWarnTime, 'warning')
      if (data.exprieToken && data.passwordWarnTime) gp.$baseMessage(data.exprieToken + data.passwordWarnTime, 'warning')
      if (data.exprieToken && !data.passwordWarnTime) gp.$baseMessage(data.exprieToken, 'warning')
      if (data.passwordWarnTime && !data.exprieToken) gp.$baseMessage(data.passwordWarnTime, 'warning')
      commit('setLanguage', userInfo.LANGUAGE_CODE)
      commit('setUid', data.USER_ID)
      commit('setToken', data.token)
      commit('setApps', data.app)

      if (loginMessage) {
        // const hour = new Date().getHours()
        // const thisTime = hour < 8 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
        if (data.exprieToken) {
          // gp.$baseMessage(data.passwordWarnTime ? data.passwordWarnTime + ',' + data.exprieToken : data.exprieToken, 'warning')
        } else {
          // gp.$baseNotify(`欢迎登录${title}`, `${thisTime}！`)
        }
      }
    } else {
      const err = `${translateTitle('Base.login.登录接口异常')}${tokenName}...`
      gp.$baseMessage(err, 'error')
      throw err
    }
    return data
  },
  /**
   * @description 获取用户信息接口 这个接口非常非常重要，如果没有明确底层前逻辑禁止修改此方法，错误的修改可能造成整个框架无法正常使用
   * @param {*} { commit, dispatch, state }
   * @returns
   */
  async getUserInfo({ commit, dispatch, state, getters }, datas) {
    const data = await getUserInfo({
      appId: state.appId,
      appCode: datas.appCode || state.appCode,
      language: state.language || '',
      datas: datas,
    })

    console.log('测试用户请求(误删,后面报错可查看)', data)

    let _data = data.data
    // this.$store.dispatch('user/setToken', data.token)
    commit('setToken', _data.token)
    let { userName: username, menu, botton, warehouseList, currentWarehouseInfo, app, pdaUrl } = _data
    let wareHoseId = (currentWarehouseInfo && currentWarehouseInfo[0] && currentWarehouseInfo[0].WAREHOUSE_ID) || ''
    let constData = {}
    const reg = new RegExp('^#(.*?)#') //#号开头#结尾
    for (const key in _data) {
      if (reg.test(key)) {
        constData[key] = _data[key]
      }
    }
    state.pdaUrl = pdaUrl

    commit('setMenuBtns', botton || [])
    commit('setMenu', menuToRoutes(menu, state.appCode.toLowerCase()))
    if (!state.language) {
      commit('setLanguage', 'zh_CN')
    }
    //websocket 启动
    setTimeout(() => {
      WebSocketConnect()
    }, 3000)

    if (process.env.VUE_APP_BuildProject !== 'pda') {
      commit('setWarehouseList', warehouseList || [])
      commit('setFirstWareHoseId', isEmpty(wareHoseId) ? (isEmpty(warehouseList) ? '' : warehouseList[0]['WAREHOUSE_ID']) : wareHoseId)
    }

    commit('setApps', app || [])
    commit('setConstant', constData)
    commit('setappCodeUrl', _data.app_code_url)

    let appInfo = state.apps.find((v) => v.ID == state.appId)
    if (!isEmpty(appInfo)) {
      if (appInfo.NO_OPERATION_TIME) {
        //长时间不动 自动退出
        astrict(appInfo.NO_OPERATION_TIME)
      }
    }

    let _getAppInfo = getters.getAppInfo
    console.log(_getAppInfo)
    //添加水印功能
    if (_getAppInfo.WATERMARK_SWITCH == 'Y' && (!isEmpty(_getAppInfo.WATERMARK_TITLE) || !isEmpty(_getAppInfo.WATERMARK_DESC))) {
      let _title = constantStr(_getAppInfo.WATERMARK_TITLE, getters.getConstant)
      let _desc = constantStr(_getAppInfo.WATERMARK_DESC, getters.getConstant)
      console.log('_title', _title, _title === 'undefined')
      Watermark.set({
        title: _title,
        desc: _desc,
      })
    }

    let roles = []
    let permissions = []
    /**
     * 检验返回数据是否正常，无对应参数，将使用默认用户名,头像,Roles和Permissions
     * username {String}
     * roles {List}
     * ability {List}
     */
    if ((username && !isString(username)) || (roles && !isArray(roles)) || (permissions && !isArray(permissions))) {
      const err = translateTitle('Base.login.JSON格式错误')
      gp.$baseMessage(err, 'error')
      throw err
    } else {
      // 如不使用username用户名,可删除以下代码
      if (username) commit('setUsername', username)
      // 如不使用roles权限控制,可删除以下代码
      if (roles) dispatch('acl/setRole', roles, { root: true })
      // 如不使用permissions权限控制,可删除以下代码
      if (permissions) dispatch('acl/setPermission', permissions, { root: true })
    }
  },
  /**
   * @description 退出登录
   * @param {*} { dispatch }
   */
  async logout({ dispatch }) {
    // await logout()
    await dispatch('resetAll', {
      clear: true,
      toLoginUrl: true,
    })
  },
  /**
   * @description 重置token、roles、permission、router、tabsBar等
   * @param {*} { commit, dispatch }
   */
  async resetAll({ commit, dispatch }, { clear = false, toLoginUrl = true }) {
    console.log('重置数据')
    commit('setUid', '')
    commit('setUsername', '')
    commit('routes/setRoutes', [], { root: true })
    await dispatch('setToken', '')
    await dispatch('acl/setFull', false, { root: true })
    await dispatch('acl/setRole', [], { root: true })
    await dispatch('acl/setPermission', [], { root: true })
    await dispatch('tabs/delAllVisitedRoutes', null, { root: true })
    await resetRouter()

    clearStorage()
    console.log('重置数据 完成', {
      clear,
      toLoginUrl,
      independent,
      href: `${GFCD('common')['loginUrl']}`,
    })
    // clear: true, toLoginUrl: true, independent: true, href: 'http://192.168.3.211:84'
    let has = ['localhost', '127.0.0.1'].includes(location.hostname)
    if (toLoginUrl) {
      if (independent) {
        // location.href =
        //   process.env.VUE_APP_BuildProjectType === 'mobile'
        //     ? `http://${location.hostname}:${has ? location.port : 84}`
        //     : `${GFCD('common')['loginUrl']}`
        // 本地端口写死3000，无/pda has
        // 线上或许有端口肯定有/pda
        let str = has ? ':3000' : location.port ? `:${location.port}/pda` : '/pda'
        console.log('路径', `http://${location.hostname}${str}`)
        location.href = process.env.VUE_APP_BuildProjectType === 'mobile' ? `http://${location.hostname}${str}` : `${GFCD('common')['loginUrl']}`
      } else {
        // location.href =
        //   process.env.VUE_APP_BuildProjectType === 'mobile'
        //     ? `http://${location.hostname}:${has ? location.port : 84}${clear ? '#/?clear=true' : ''}`
        //     : `${GFCD('common')['loginUrl']}${clear ? '#/?clear=true' : ''}`
        location.href =
          process.env.VUE_APP_BuildProjectType === 'mobile'
            ? `http://${location.hostname}/pda${clear ? '#/?clear=true' : ''}`
            : `${GFCD('common')['loginUrl']}`
      }
    }
  },
  setUid({ commit }, uid) {
    commit('setUid', uid)
  },
  setbusinessCode({ commit }, businessCode) {
    commit('setbusinessCode', businessCode)
  },
  setappCodeUrl({ commit }, setappCodeUrl) {
    commit('setappCodeUrl', setappCodeUrl)
  },

  /**
   * @description 设置token
   * @param {*} { commit }
   * @param {*} token
   */
  setToken({ commit }, token) {
    commit('setToken', token)
  },
  //设置语言
  setLanguage({ commit }, language) {
    commit('setLanguage', language)
  },
  /**
   * @description 设置appid
   * @param {*} { commit }
   * @param {*} appid
   */
  setAppId({ commit }, appid) {
    commit('setAppId', appid)
  },
  /**
   * @description 设置appCode
   * @param {*} { commit }
   * @param {*} appCode
   */
  setAppCode({ commit }, appCode) {
    commit('setAppCode', appCode)
  },
  /**
   * @description 设置orgCode
   * @param {*} { commit }
   * @param {*} orgCode
   */
  setOrgCode({ commit }, orgCode) {
    commit('setOrgCode', orgCode)
  },
  /**
   * @description 获取所有应用
   * @param {*} { commit }
   * @param {*} appid
   */
  setApps({ commit }, apps) {
    commit('setApps', apps)
  },
  /**
   * @description 跳转应用
   * @param {*} { commit }
   * @param {*} appid
   */
  async toApp({ state }, item) {
    let appInfo = null
    if (item) {
      appInfo = item
    }
    // else {
    //   let _item = state.apps.find((item) => item.ID === state.appId)
    //   appInfo = _item
    //   // appInfo.orgId = _item.org.length > 0 ? _item.org[0]['ORG_ID'] : ''
    //   // appInfo.warehouseId = _item.warehouses.length > 0 ? _item.warehouses[0]['WAREHOUSE_ID'] : ''
    //   // 一样的 就直接获取了
    //   appInfo.orgId = state.orgCode
    //   appInfo.warehouseId = state.wareHoseId
    // }

    if (appInfo) {
      let _domain = `${appInfo.URL}${appInfo.URL.lastIndexOf('/') == -1 ? '/' : ''}`
      //开发模式直接跳转
      let hasLocalhot = ['localhost'].includes(location.hostname)
      _domain = hasLocalhot ? `http://localhost:3000/` : _domain

      let _obj = {
        systemApp: appInfo.APP_CODE,
        tk: item.tk || getStorage(`token_${getUrlSystemApp()}`),
        appid: appInfo.ID,
        appCode: appInfo.APP_CODE,
        domain: _domain,
        uid: state.uid,
        language: state.language,
        appInfo: appInfo,
      }
      let _query = qs.stringify(_obj)

      console.log('toApp页面', `${_domain}#/toapp?${_query}`, _obj)
      setTimeout(() => {
        location.href = `${_domain}#/toapp?${_query}`
        // window.open(`${_domain}#/toapp?${_query}`)
      }, 1)
    }
  },

  async toPda({ state }) {
    let pdaUrl = state.pdaUrl
    let _domain = `${pdaUrl}${pdaUrl.lastIndexOf('/') == -1 ? '/' : ''}`
    let _obj = {
      tk: getStorage(`token_${getUrlSystemApp()}`),
      domain: _domain,
      uid: state.uid,
      language: state.language,
      appid: state.appId,
      appCode: state.appCode,
      wareHoseId: state.businessCode.WAREHOUSE_ID,
      orgId: state.businessCode.ORG_ID,
    }
    let _query = qs.stringify(_obj)
    // 192.168.3.19
    console.log('Nico跳转pda18:20', `${_domain}#/to?${_query}`)
    window.open(`${_domain}#/to?${_query}`)
  },

  /**
   * @description 切换应用
   * @param {*} { commit }
   * @param {*} appid
   */
  //{state, dispatch }
  async switchApp({ state }, item) {
    let appInfo = item || state.apps.find((item) => item.ID === state.appId)
    if (appInfo) {
      let _query = qs.stringify({
        appid: appInfo.ID,
        back: item.back || false,
        tk: getStorage(`token_${getUrlSystemApp()}`), //token不用 因为是统一平台共用
        appCode: appInfo.APP_CODE,
        language: state.language,
        // apps: state.apps,
        // systemApp: 'login',
        // orgCode: appInfo.ORG_CODE,
        // domain: `${appInfo.URL}${appInfo.URL.lastIndexOf('/') == -1 ? '/' : ''}`,
      })
      // await dispatch('resetAll', {
      //   clear: true,
      //   toLoginUrl: false,
      // })
      let _loginUrl = `${GFCD('common')['loginUrl']}`
      // location.href = `${_loginUrl}#/apps?${_query}`
      window.open(`${_loginUrl}#/apps?${_query}`)
    }
  },
  /**
   * @description 切换仓库
   * @param {*} { commit }
   */
  async switchWarehouse({ state, commit }, item) {
    const data = await switchWarehouse(item)
    console.log('切换仓库 ', data)
    if (data.code === '00000') {
      const newConstant = cloneDeep(state.constant)
      newConstant['#WH_ID#'] = item.WAREHOUSE_ID
      const newBusinessCode = cloneDeep(state.businessCode)
      newBusinessCode['WAREHOUSE_ID'] = item.WAREHOUSE_ID
      commit('setbusinessCode', newBusinessCode)
      commit('setConstant', newConstant)
      // state.wareHoseId = item.WAREHOUSE_ID
      setStorage(`wareHoseId_${getUrlSystemApp()}`, item.WAREHOUSE_ID)
      location.reload()
    } else {
      gp.$baseMessage(data.message || translateTitle('Base.login.切换失败'), 'warning')
    }
  },
  setWarehouseList({ commit }, list) {
    commit('setWarehouseList', list)
  },
  setFirstWareHoseId({ commit }, id) {
    commit('setFirstWareHoseId', id)
  },
  setConstant({ commit }, vals) {
    commit('setConstant', vals)
  },
}
export default { state, getters, mutations, actions }
